import { Context } from 'koa'
import { AppDataSource } from '../data-source'
import * as argon from 'argon2'
import * as jwt from 'jsonwebtoken'

import { User } from '../entity/User'
import { JWT_SECRET } from '../util/constants'
import { sucessCode, warnCode, errCode } from '../util/crudUtil'

const userRepo = AppDataSource.getRepository(User)
export default class AuthController {
  public static async login(ctx: Context) {
    const info: any = ctx.request.body
    const user = await userRepo.findOne({
      where: {
        name: info.name,
      },
      select: {
        password: true,
      },
    })

    if (!user) {
      warnCode(ctx, 300, '用户不存在')
    } else if (await argon.verify(user.password, info.password)) {
      ctx.body = {
        token: jwt.sign({ id: user.id }, JWT_SECRET, { expiresIn: '3h' }),
      }
    } else {
      warnCode(ctx, 401, '密码错误')
    }
  }

  public static async register(ctx: Context) {
    const info: any = ctx.request.body
    // 判断对象是否存在标志位
    let isState = false
    await userRepo
      .findOne({
        where: {
          name: info.name,
        },
      })
      .then((res) => {
        if (res) isState = true
      })
      .catch((err) => {
        errCode(ctx, 500, '注册时出现异常', err)
      })
    // 判断用户是否存在
    if (isState) return warnCode(ctx, 300, '用户名已存在')

    const newUser = new User()
    newUser.name = info.name
    newUser.email = info.email
    newUser.password = await argon.hash(info.password)

    // 保存到数据库
    await AppDataSource.manager.save(newUser)
    sucessCode(ctx, 201, '注册成功')
  }
}
